<template>
  <div class="detail">
      <div>
          <Form :model="formItem" class="form" ref="formItem" :rules="ruleValidate" :label-width="100" >
          <div class="title">
            <span>基础信息</span>
          </div>
          <FormItem label="商品名字" prop="goods_name">
            <Input v-model="formItem.goods_name" placeholder="最多输入50个字符"></Input>
          </FormItem>
          <FormItem>
            <p class="upload_font">建议尺寸：800*800像素</p>
          </FormItem>
          <FormItem label="商品轮播图" prop="goods_images">
            <template>
              <div class="demo-upload-list" v-for="(item,index) in formItem.goods_images">
                <img :src='$imgUrl +item'>
                <div class="demo-upload-list-cover">
                  <Icon type="ios-trash-outline"  @click.native="handleRemovegoods(index)"></Icon>
                </div>
              </div>
              <Upload
              :action="$imgApi"
              :on-success="handlebannerSuccess"
              :data="uploadClient"
              :show-upload-list="false"
              name="files" >
                <div class="upload">
                  <span>+添加图片</span>
                </div>
              </Upload>
            </template>
          </FormItem>
          <FormItem>
            <p class="upload_font">建议尺寸：800*800像素</p>
          </FormItem>
          <FormItem label="商品视频" prop="video">
            <template>
              <template>
                  <Upload
                  :action="$videoApi"
                  :on-success="handleVidiosuccess"
                  :data="uploadClient"
                  :show-upload-list="false"
                  :on-progress ="handleVidioprogress"
                  name="files">
                      <div class="upload">
                        <video v-if="uploadvidoeVisible" height="100%" width="100%" :src='$imgUrl +formItem.video_url'></video>
                        <span v-else>+添加视频</span>
                        <div v-show="loadingVideo" class="progress">
                          <Progress hide-info  :percent="uploadVideopercent" />
                        </div>
                      </div>
                  </Upload>
              </template>
              <template>
                <Upload :action="$imgApi"
                :on-success="handlevideoimageSuccess"
                :data="uploadClient"
                name="files"
                :show-upload-list="false"
                :on-progress ="handleprogress">
                  <div class="upload">
                    <img v-if="uploadimgVisible" :src='$imgUrl +formItem.video_image_url'>
                    <span v-else>+封面图片</span>
                    <div v-show="loadingStatus" class="progress">
                      <Progress hide-info  :percent="uploadImgpercent" />
                    </div>
                  </div>
                </Upload>
              </template>
            </template>
          </FormItem>
          <FormItem>
            <p class="upload_font">建议时长9-30秒，建议视频宽高比1:1</p>
          </FormItem>
          <FormItem label="商品分类" prop="category_id">
            <div class="category">
              <Select v-model="formItem.category_id" style="width:200px" v-if="group.length > 0">
                <Option v-for="item in group" :value="item.category_id" :key="item.category_id">{{ item.name }}</Option>
              </Select>
              <Button v-else @click="addCate">去添加分类</Button>
            </div>
          </FormItem>
          <div class="title">
             <span>规格/库存/价格</span>
          </div>
          <FormItem label="商品规格" prop="specifications">
            <div class="sku" v-for="(item,index) in formItem.specifications">
              <div class="sku_name">
                <span>规格名:</span>
                <Input  v-model="item.specifications_name" class='form-control' value='' style="width: 300px" />
                <span class="closeCate" @click="deleteName(index)"><Icon size="20" type="md-close-circle" /></span>
              </div>
              <div class="sku_info">
                <div>
                  <div class="sku_value"  v-for="(value,key) in item.specifications_value">
                    <span>规格值:</span>
                    <div>
                      <div>
                         <Input  v-model="value.value" class='form-control' value='' style="width: 300px" />
                      </div>
                      <div>
                        <Upload :action="$imgApi"
                          :on-success="handlethumbSuccess"
                          :data="uploadClient"
                          name="files"
                          :show-upload-list="false"
                          >
                            <div class="upload sku_upload" @click="clickUpload(index,key)">
                              <img v-if="value.thumbnail_url" :src='$imgUrl + value.thumbnail_url'>
                              <span v-else>+</span>
                            </div>
                        </Upload>
                      </div>
                    </div>
                  </div>
                </div>
                <Button class="addskuvalue" type="text"  @click="addSkuValue(index)">添加规格值</Button>
              </div>
            </div>
            <div class="sku_name">
              <Button  @click="addSku">添加规格</Button>
            </div>
          </FormItem>
          <FormItem>
            <p class="upload_font">如有颜色、尺寸等多种规格，请添加商品规格</p>
          </FormItem>
          <FormItem label="商品详情" prop="detail_images">
            <template>
               <tinymce  ref="editor" v-model= "formItem.detail_images"></tinymce>
            </template>
          </FormItem>
          <div class="buttonList">
              <Button class="Submit" @click="handleClose">取消</Button>
              <Button type="primary" class="Submit" @click="handleSubmit">确定</Button>
          </div>
        </Form> 
      </div>
  </div>
</template>
<script>
import tinymce from '@/components/tinymce'
export default {
   data() {
    return {
      uploadList: [],
      goods_id:false,
      group:[],
      index:'',
      key:'',
      uploadImgpercent:0,
      uploadVideopercent:0,
      loadingStatus: false,
      loadingVideo:false,
      uploadimgVisible:false,
      uploadvidoeVisible:false,
      uploadthumbnailVisible:false,
      sku_info:[],
      uploadClient:{},
      formItem: {
          goods_name: '',
          detail_images:[],
          goods_images: [],
          sale_price: '',
          video_url:'',
          video_img_url:0,
          specifications: [
          ],
          sku_info: [
          ],
      },
      ruleValidate: {
          goods_name: [
              { required: true, message: '请填写材料名字', trigger: 'blur' },
              { type: 'string', max: 50, message: '材料名字不能超过50个字符', trigger: 'blur' }
          ],
          detail_images: [
              { required: true, message: '请上传材料详情图', trigger: 'blur' },
          ],
          goods_images: [
              { required: true, message: '请上传材料轮播图', trigger: 'blur' }
          ],
          video_url: [
              { required: true, message: '请上传材料视频', trigger: 'blur' }
          ],
          category_id: [
              { required: true, message: '请选择材料分类', trigger: 'blur' },
          ],
      },
    }
  },
  watch : {
    'formItem.specifications':{
        handler:function(specifications){       
          let valueArray = []
          let allArray = []
          for (var i = 0 ; i < specifications.length ;  i++) {
             valueArray = specifications[i].specifications_value.map(item=>{
                     return item.value
             })
             allArray.push(valueArray)
          }
          let sku = this.cartesianProductOf.apply(this,allArray);  //调用笛卡尔积方法
          let name = []
          for (var i = 0 ; i < sku.length ;  i++) {
              let sku_info = {
                  sku_name :  sku[i]
              }
              name.push(sku_info)
          }
          this.formItem.sku_info = name
        },
        deep: true
      }
  },
  mounted() {
    this.uploadClient = {
      session_id: this.Cookies.get('session')
    }
    this.getGoodsgroup()
    if(this.$route.params.id){
       this.getGoods();
    }
  },
  methods: {
    deleteName(index){
      this.formItem.specifications.splice(index,1)
    },
    cartesianProductOf:function(){ //笛卡尔积
      return Array.prototype.reduce.call(arguments,function(a, b) {
      var ret = [];
        a.forEach(function(a) {
          b.forEach(function(b) {
             ret.push(a.concat([b]));
          });
        });
      console.log(ret)  //组合成功   
      return ret;
      }, [[]]);
    },
    addSku(){
      let specifications = {
        specifications_name:'',
        specifications_value:[
          {
            value:'',
            thumbnail_url:''
          }
        ]
      }     
      this.formItem.specifications.push(specifications)
    },
    addSkuValue(index){
      let specifications_value = {
        value:'',
        thumbnail_url:''
      }
      this.formItem.specifications[index].specifications_value.push(specifications_value)
    },
    getGoods(){
      let params = {
          goods_id:this.$route.params.id
      }
      this.$api.getGoodsdetail(params)
          .then(res => {
            if (res.code == 200) {
              this.formItem.goods_name = res.data.goods_name
              this.formItem.detail_images = res.data.detail.map(item =>{
                    return item.image_url
              });
              this.formItem.goods_images = res.data.images.map(item =>{
                    return item.image_url
              });
              this.formItem.video_url =  res.data.video_url
              this.formItem.category_id = res.data.category_id
              this.formItem.video_image_url =  res.data.video_img_url
              this.uploadimgVisible = true
              this.uploadvidoeVisible = true
              this.formItem.specifications = res.data.specifications
              this.formItem.sku_info = res.data.sku_info
            }
      })
    },
    handleRemove (index) {
      this.formItem.detail_images.splice(index,1);
    },
    handleRemovegoods(index){
      this.formItem.goods_images.splice(index,1);
    },
    handleSuccess(res,file) {
      console.log(res,file)
      if (res.code == 200) {
        this.$Message.success('上传成功')
        let imgobj = res.data
        this.formItem.detail_images.push(imgobj)
        console.log(this.formItem.detail_images);
      }else if (res.code == 500) {
        this.$Message.error(res.msg)
      }
    },
    clickUpload(index,key){
      this.index = index 
      this.key = key
    },
    handlebannerSuccess(res,file) {
      console.log(res,file)
      if (res.code == 200) {
        this.$Message.success('上传成功')
        let imgobj = res.data
        this.formItem.goods_images.push(imgobj)
      }
    },
    handlethumbSuccess(res,file) {
      if (res.code == 200) {
        this.$Message.success('上传成功')
        let imgobj = res.data
        this.formItem.specifications[this.index].specifications_value[this.key].thumbnail_url = imgobj
      }else if (res.code == 500) {
        this.$Message.error(res.msg)
      }
    },
    addCate(){
      this.$router.push({
        name: "dataCate"
      });
    },
    handleprogress(event){
      this.uploadImgpercent = event.percent
      this.loadingStatus = true;
    },
    handlevideoimageSuccess(res,file) {
      console.log(res,file)
      if (res.code == 200) {
        this.$Message.success('上传成功')
        this.loadingStatus = false;
        this.formItem.video_image_url =  res.data
        this.uploadimgVisible = true
      }
    },
    handleVidioprogress(event){
      this.uploadVideopercent = event.percent
      this.loadingVideo = true;
    },
    handleVidiosuccess(res,file) {
      console.log(res,file)
      if (res.code == 200) {
        this.$Message.success('上传成功')
        this.loadingVideo = false;
        this.formItem.video_url =  res.data
        this.uploadvidoeVisible = true
      }
    },
    uploadthumbnail(index,i){
      console.log(index,i);
      this.specificationsId = index
      this.specifications_valueId = i
    },
    handlethumbnailSuccess(res,file){
      if (res.code == 200) {
        this.$Message.success('上传成功')
        this.formItem.specifications[this.specificationsId].specifications_value[this.specifications_valueId].thumbnail_url =  res.data
        console.log(this.formItem.specifications);
        this.uploadthumbnailVisible = true
      }
    },
    getGoodsgroup(){
      let params = {}
      this.$api.getcategory(params)
          .then(res => {
            console.log(res);
            if (res.code == 200) {
              this.group = res.data.data
              console.log(this.group)
        }
      })
    },
    handleClose(){
       this.$router.go(-1)          
    },
    handleSubmit(value){
      if (this.$route.params.id) {
        let params = {
          goods_id :  this.$route.params.id,
          goods_name: this.formItem.goods_name,
          detail_images:  this.formItem.detail_images,
          goods_images:    this.formItem.goods_images,
          video_url: this.formItem.video_url,
          video_img_url:   this.formItem.video_image_url,
          category_id:   this.formItem.category_id,
          specifications: this.formItem.specifications,
          sku_info:    this.formItem.sku_info,
        };
        this.$api.editGoods(params)
          .then(res => {
            console.log(res);
            if (res.code == 200) {
              this.$Message.success('修改成功');
              this.$router.push({
                name:'goodsList'
              })
            }
        })
      }else{
        let params = {
          goods_name: this.formItem.goods_name,
          detail_images:  this.formItem.detail_images,
          goods_images:    this.formItem.goods_images,
          video_url: this.formItem.video_url,
          video_img_url:   this.formItem.video_image_url,
          category_id:   this.formItem.category_id,
          specifications: this.formItem.specifications,
          sku_info:    this.formItem.sku_info,
        }
        this.$api.createGoods(params)
          .then(res => {
            console.log(res);
            if (res.code == 200) {
              this.$Message.success('添加成功');
              this.$router.push({
                name:'goodsList'
              })
            }
        })
      }
    },
  },
  components: {
     tinymce
  }
}
</script>
<style lang="less" scoped>
    @import './index.less';
</style>
